<template>
  <div class="pie">
    <div class="chart">
      <chart :option="refChartOption" :style="{ height: `${chartHeight}` }" />
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, onMounted, ref, watch } from 'vue';
import { Chart, SeriesDataItem } from '@/components';
import { EChartOption } from 'echarts';

type PieDataType = number[] | number[][] | EChartOption.SeriesPie.DataObject[];

export default defineComponent({
  name: 'Pie',
  props: {
    data: {
      type: Array as PropType<SeriesDataItem[]>,
      default: () => [],
    },
    height: {
      type: Number,
      default: 0,
    },
  },
  setup(props) {
    const chartOption = {
      color: ['#1790ff', '#12c2c2', '#2fc25b', '#f04864', '#8542e0'],
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          name: '涉' + '警情',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center',
          },
          labelLine: {
            show: false,
          },
          data: [] as PieDataType,
        },
      ],
    };
    const refChartOption = ref(chartOption);

    const chartHeight = computed(() => `${props.height + 100}px`);
    const setChartOption = (data: any[]) => {
      const xAxis: string[] = [];
      const seriesData: EChartOption.SeriesPie.DataObject[] = [];
      data.forEach(item => {
        const { name, value } = item;
        xAxis.push(name);
        seriesData.push({
          name,
          value,
        });
      });
      refChartOption.value.series[0].data = seriesData;
    };

    watch(
      () => props.data,
      () => {
        setChartOption(props.data);
      },
    );

    onMounted(() => {
      setChartOption(props.data);
    });
    return {
      chartHeight,
      refChartOption,
      setChartOption,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style lang="less" scoped>
@import './index.less';
</style>
